package com.sunda.spmswms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmswms.entity.SapDeliveryNote;
import com.sunda.spmswms.entity.SapDeliveryNoteDtl;
import com.sunda.spmswms.mapper.SapDeliveryNoteDtlMapper;
import com.sunda.spmswms.mapper.SapDeliveryNoteMapper;
import com.sunda.spmswms.service.ISapDeliveryNoteLogService;
import com.sunda.spmswms.service.ISapDeliveryNoteMService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;

import static com.sunda.spmscommon.Constans.SUCCESS;

/**
 * <p>
 * SAP交货单表头 服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2021-03-22
 */
@Service
public class SapDeliveryNoteMServiceImpl extends ServiceImpl<SapDeliveryNoteMapper, SapDeliveryNote> implements ISapDeliveryNoteMService {

    @Autowired
    SapDeliveryNoteDtlMapper sapDeliveryNoteDtlMapper;

    @Autowired
    ISapDeliveryNoteLogService iSapDeliveryNoteLogService;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     {
     "sapDeliveryNoteDtls": [{
     "documentDate": null,
     "materialNo": "210030763",
     "qtySales": null,
     "deliveryNoteSapItem": 10,
     "postingDate": null,
     "itemStatus": "0",
     "whsLocationCode": "1011",
     "actualQtySales": null,
     "updateTime": "2021-08-09 02:35:05",
     "tempStorage": null,
     "spmsItem": 10,
     "werks": "CN01",
     "receivedQty": null,
     "deliveryNoteSap": "10000",
     "remarks": null,
     "operator": "张三"
     },
     {
     "documentDate": null,
     "materialNo": "130012803",
     "qtySales": null,
     "deliveryNoteSapItem": 20,
     "postingDate": null,
     "itemStatus": "0",
     "whsLocationCode": "1011",
     "actualQtySales": null,
     "updateTime": "2021-08-09 02:35:05",
     "tempStorage": null,
     "spmsItem": 20,
     "werks": "CN01",
     "receivedQty": null,
     "deliveryNoteSap": "10000",
     "remarks": null,
     "operator": "张三"
     },
     {
     "documentDate": null,
     "materialNo": "130000131",
     "qtySales": null,
     "deliveryNoteSapItem": 30,
     "postingDate": null,
     "itemStatus": "0",
     "whsLocationCode": "1011",
     "actualQtySales": null,
     "updateTime": "2021-08-09 02:35:05",
     "tempStorage": null,
     "spmsItem": 30,
     "werks": "CN01",
     "receivedQty": null,
     "deliveryNoteSap": "10000",
     "remarks": null,
     "operator": "张三"
     },
     {
     "documentDate": null,
     "materialNo": "130000131",
     "qtySales": null,
     "deliveryNoteSapItem": 40,
     "postingDate": null,
     "itemStatus": "0",
     "whsLocationCode": "1011",
     "actualQtySales": null,
     "updateTime": "2021-08-09 02:35:05",
     "tempStorage": null,
     "spmsItem": 40,
     "werks": "CN01",
     "receivedQty": null,
     "deliveryNoteSap": "10000",
     "remarks": null,
     "operator": "张三"
     }
     ],
     "sapDN": {
     "deliveryNoteSap": "10000",
     "updateTime": "2021-08-09 01:32:14"
     },
     "targetStatus": "3" //3表示保存；8表示提交SAP；
     }
     * @param doc
     * @return
        交货单贸易货行项目状态（默认0-待到货；3-收货中；7-提交SAP失败；8-提交SAP完成；11-删除/关闭；12-已撤销；）
        1.根据交货单更新时间判断当前数据是否最新版本；不是则提示错误；
        2.此接口忽略行数据状态为 8、11、12 的数据；targetStatus：3表示保存；8表示提交SAP；
        3.保存功能：根据前端提交数据，以及更新时间判断是否最新数据，更新状态为 0、3、7 全部行数据当前状态；
        SPMS行号字符长度大于6为新增行数据，新增行数据状态为 3；
        4.提交SAP功能：先按步骤2执行保存功能；然后将送货单下状态为 3、7 的 RECEIVED_QTY 大于0的行查询出来提交SAP；
            4.1.提交成功：更新这些行数据库存、记录单据日志、记录提交SAP日志、更新这些行状态为 8-提交SAP完成.
            4.2.提交失败：忽略库存更新、记录单据日志、记录提交SAP日志、更新这些行状态为 7-提交SAP失败；返回SAP错误信息给前端；
            4.3.提交异常：忽略库存更新、忽略单据日志等日志记录；返回异常信息给前端；
        5.更新交货单的 SPMS_STATUS = 3-收货中；
        6.返回该交货单数据库最新版的 交货单表头、交货单明细 最新版数据；
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized ResponseResult saveSapDeliveryNote(JSONObject doc, String userId) {
        ResponseResult result =  checkDocValidate (doc, userId);
        if (result.getCode() != SUCCESS){
            return result;
        }
        if (result.getCode() == SUCCESS){
            return result.add("message", "接口未完成");
        }
        ResponseResult updateResult = saveDNDtl(doc, userId);
        if ("8".equals(doc.getString("targetStatus"))){
            String deliveryNoteSap = doc.getJSONObject("sapDN").getString("deliveryNoteSap");
            //TODO 查询获取 3-收货中；7-提交SAP失败；状态实际收货数量大于0的行，提交SAP；————20210809
        }

        return ResponseResult.success().add("a", "b");
    }


    ResponseResult saveDNDtl (JSONObject doc, String userId){
        String deliveryNoteSap = doc.getJSONObject("sapDN").getString("deliveryNoteSap");
        String updateTime = doc.getJSONObject("sapDN").getString("updateTime");
        QueryWrapper<SapDeliveryNote> queryWrapper = new QueryWrapper<SapDeliveryNote>().eq("DELIVERY_NOTE_SAP", deliveryNoteSap);
        SapDeliveryNote dn = this.baseMapper.selectOne(queryWrapper);
        dn.setSpmsStatus("3");
        this.baseMapper.update(dn, queryWrapper);
        iSapDeliveryNoteLogService.insertSapDeliveryNoteLogM(deliveryNoteSap, userId, "更新交货单");

        for(int i = 0; i < doc.getJSONArray("sapDeliveryNoteDtls").size(); i++){
            JSONObject dnDtlObj = doc.getJSONArray("sapDeliveryNoteDtls").getJSONObject(i);
            String itemDeliveryNoteSap = dnDtlObj.getString("deliveryNoteSap");
            String spmsItem = dnDtlObj.getString("spmsItem");
            if (spmsItem.length() > 6){
                insertSapDeliveryNoteDtl(dnDtlObj, userId);
            }else{
                QueryWrapper<SapDeliveryNoteDtl> wrapper = new QueryWrapper<SapDeliveryNoteDtl>().eq("DELIVERY_NOTE_SAP", itemDeliveryNoteSap).eq("SPMS_ITEM", spmsItem);
                SapDeliveryNoteDtl sapDeliveryNoteDtl = sapDeliveryNoteDtlMapper.selectOne(wrapper);
                if (sapDeliveryNoteDtl != null && !"8".equals(sapDeliveryNoteDtl.getItemStatus()) && !"11".equals(sapDeliveryNoteDtl.getItemStatus())
                        && !"12".equals(sapDeliveryNoteDtl.getItemStatus())){
                    sapDeliveryNoteDtl.setReceivedQty(StringUtils.isEmpty(dnDtlObj.getString("receivedQty")) ? 0 : dnDtlObj.getDouble("receivedQty"));
                    sapDeliveryNoteDtl.setActualQtySales(StringUtils.isEmpty(dnDtlObj.getString("actualQtySales")) ? 0 : dnDtlObj.getDoubleValue("actualQtySales"));
                    sapDeliveryNoteDtl.setTempStorage(dnDtlObj.getJSONArray("tempStorage") == null ? "[]" : dnDtlObj.getJSONArray("tempStorage").toJSONString());
                    sapDeliveryNoteDtl.setRemarks(dnDtlObj.getString("remarks"));
                    sapDeliveryNoteDtl.setDocumentDate(dnDtlObj.getString("documentDate"));
                    sapDeliveryNoteDtl.setUserId(userId);
                    sapDeliveryNoteDtl.setOperator(dnDtlObj.getString("operator"));
                    if ("0".equals(sapDeliveryNoteDtl.getItemStatus())){
                        sapDeliveryNoteDtl.setItemStatus("3");
                    }
                    sapDeliveryNoteDtlMapper.update(sapDeliveryNoteDtl, wrapper);
                }
            }
        }
        return ResponseResult.success();
    }

    ResponseResult checkDocValidate (JSONObject doc, String userId) {
        try {
            if (null == doc || StringUtils.isEmpty(userId) || !doc.containsKey("targetStatus") ||
                    StringUtils.isEmpty(doc.getString("targetStatus"))){
                return ResponseResult.error("请求参数错误");
            }
            if (!doc.containsKey("sapDN") || null == doc.getJSONObject("sapDN") || StringUtils.isEmpty(doc.getJSONObject("sapDN").getString("deliveryNoteSap"))){
                return ResponseResult.error("请求参数中交货单不能为空");
            }
            if (!doc.containsKey("sapDeliveryNoteDtls") || doc.getJSONArray("sapDeliveryNoteDtls").size() == 0){
                return ResponseResult.error("请求参数中交货单明细行不能为空");
            }
            String deliveryNoteSap = doc.getJSONObject("sapDN").getString("deliveryNoteSap");
            String updateTime = doc.getJSONObject("sapDN").getString("updateTime");
            SapDeliveryNote dn = this.baseMapper.selectOne(new QueryWrapper<SapDeliveryNote>().eq("DELIVERY_NOTE_SAP", deliveryNoteSap));
            if (null == dn || !updateTime.equals(sdf.format(dn.getUpdateTime()))){
                return ResponseResult.error("数据不存在或已被更新请刷新后重试");
            }
            if (StringUtils.isNotEmpty(dn.getPackageNote())){
                return ResponseResult.error("备件收货不适用此方法");
            }
            return ResponseResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error().add("error", e.getMessage());
        }
    }

    void insertSapDeliveryNoteDtl (JSONObject dnDtlObj, String userId){
        SapDeliveryNoteDtl deliveryNoteDtl = new SapDeliveryNoteDtl();
        deliveryNoteDtl.setDeliveryNoteSap(dnDtlObj.getString("deliveryNoteSap"));
        deliveryNoteDtl.setDeliveryNoteSapItem(dnDtlObj.getInteger("deliveryNoteSapItem"));
        deliveryNoteDtl.setMaterialNo(dnDtlObj.getString("materialNo"));
        deliveryNoteDtl.setWerks(dnDtlObj.getString("werks"));
        deliveryNoteDtl.setWhsLocationCode(dnDtlObj.getString("whsLocationCode"));
        deliveryNoteDtl.setReceivedQty(StringUtils.isEmpty(dnDtlObj.getString("receivedQty")) ? 0 : dnDtlObj.getDouble("receivedQty"));
        deliveryNoteDtl.setItemStatus("3");
        deliveryNoteDtl.setRemarks(dnDtlObj.getString("remarks"));
        deliveryNoteDtl.setTempStorage(dnDtlObj.getJSONArray("tempStorage") == null ? "[]" : dnDtlObj.getJSONArray("tempStorage").toJSONString());
        deliveryNoteDtl.setActualQtySales(StringUtils.isEmpty(dnDtlObj.getString("actualQtySales")) ? 0 : dnDtlObj.getDoubleValue("actualQtySales"));
        deliveryNoteDtl.setDocumentDate(dnDtlObj.getString("documentDate"));
        deliveryNoteDtl.setUserId(userId);
        deliveryNoteDtl.setOperator(dnDtlObj.getString("operator"));
        sapDeliveryNoteDtlMapper.insert(deliveryNoteDtl);
    }


}



